package cn.flyingocean;

import cn.flyingocean.exception.NoSpiderJoined;
import cn.flyingocean.exception.SpiderException;
import cn.flyingocean.spider.Spider;

import java.util.ArrayList;
import java.util.List;

public class SpiderManager {

    private List<Spider> spiders = new ArrayList<Spider>();

    /**
     * 将Spider 加入到当前的抓取任务中，join可理解为“加入”、“联接”、“连接”
     * @param spider
     */
    public void join(Spider spider){
        spiders.add(spider);
    }

    /**
     * 开始抓取任务
     * @return
     * @throws NoSpiderJoined
     */
    public Object startTask() throws SpiderException {
        Spider executor = spiders.get(0);
        // 中间结果
        Object mid  = null;
        // 如果没有一个Spider join
        if (executor==null){
            throw new NoSpiderJoined();
        }
        // 先执行第一个
        mid = executor.doWork();
        executor.onCompleted(mid);

        for (int i=1;i<spiders.size();i++){
            executor = spiders.get(i);
            mid = executor.doWork(mid);
            executor.onCompleted(mid);
        }
        return mid;
    }

    /**
     * 关闭 Manager，调用所有 spider 的 beforeDead() 方法
     */
    public void closeManager(){
        for (int i=0;i<spiders.size();i++){
            spiders.get(i).beforeDead();
        }
    }
}
